<?php
/**
 * 面具性格
 * User: xieliang
 * Date: 2018-11-14
 * Time: 10:09
 */

namespace app\api\controller;

use think\Controller;
use think\Cache;
use think\Session;
use think\cache\driver\Redis;
use app\api\controller\Fortune;
use think\Log;
use app\common\model\WechatUserModel as UserModel;

/**
 * 公众号自动回复
 *
 * Class Mjxigcallback
 * @package app\api\controller
 */
class fuben extends Controller
{

    public function index()
    {
        if (!isset($_GET['echostr'])) {
            $this->respond();
        } else {
            $this->valid();
        }
    }

    /**
     * 验证签名
     */
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'yixiaowai';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
    }


    /**
     * 微信回调接口入口方法
     * @var object
     * @return string
     */
    public function respond()
    {
        $postStr = file_get_contents("php://input");
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr);
            $RX_TYPE = trim($postObj->MsgType);
            //客户所在公众号openid
            $openid = addslashes($postObj->FromUserName);
            //公众号原始id
            $original_id = addslashes($postObj->ToUserName);

            switch($RX_TYPE){
                case "event"://事件
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text"://文本回复
                    $result = $this->receiveText($postObj);
                    break;
                case "image"://图片
                    $result = $this->receiveImage($postObj);
                    break;
                case "location"://地址
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice"://声音
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video"://视频
                    $result = $this->receiveVideo($postObj);
                    break;
                case "link"://链接
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknown msg type: ".$RX_TYPE;
                    break;
            }

            echo $result;
        }else{
            echo "";
            exit;
        }
    }

    /**
     * 接收事件
     */
    private function receiveEvent($object){
        $content = "";
        switch($object->Event){
            case "subscribe"://关注事件（带参数二维码扫描事件）
                $content = $this->subscribe_Event($object);
                break;
            case "unsubscribe"://取消关注事件
                $this->unsubscribe_Event($object);
                break;
            case "SCAN"://已关注用户扫描带参数二维码事件
                $content = "";
                break;
            case "CLICK"://自定义菜单点击推送关键字事件
                $content = $this->click_Event($object);
                break;
            case "LOCATION"://上报地理位置事件
                $content='';
                break;
            case "VIEW"://自定义菜单点击跳转URL接事件
                $content='';
                break;
            case "MASSSENDJOBFINISH"://事件推送群发结果
                $content='';
                break;
            default:
                $content='';
                break;
        }

        if(is_array($content)){
            if (isset($content[0])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }

        return $result;
    }

    /**
     * 关注事件
     */
    private function subscribe_Event($object){
        $openid = addslashes($object->FromUserName);
        $original_id = addslashes($object->ToUserName);
        $userinfo = $this->getwuserinfo($openid,$original_id);
        if(intval($userinfo['subscribe']) != 0){
            $access_token = $this->getAccessToken($original_id);

            //查询数据库是否存在，已存在且是未关注更改状态
            $user = new UserModel();
            $where['openid'] = $openid;
            $where['originalid'] = $original_id;
            $res = $user->getOne($where);
            if(!$res){
                //如果数据库没有用户信息
                $data['openid'] = $openid;
                $data['originalid'] = $original_id;
                $data['nickname'] = $userinfo['nickname'];
                $data['sex'] = $userinfo['sex'];
                $data['headimgurl'] = $userinfo['headimgurl'];
                $data['isgz'] = 1;
                $data['gztime'] = time();
                $data['qgtime'] = 0;
                $data['addtime'] = time();
                $data['uptime'] = time();
                $ress = $user->save($data);
            }else{
                if($res['isgz'] == 1) return "";
                //更新用户信息
                $data['nickname'] = $userinfo['nickname'];
                $data['headimgurl'] = $userinfo['headimgurl'];
                $data['isgz'] = 1;
                $data['gztime'] = time();
                $data['uptime'] = time();
                $ress = $user->save($data,$where);
            }

            //当前答题编号
            $redis_timu_key = 'timu_'.$original_id.'_'.$openid;
            //当前总积分
            $redis_jf_key = 'jifen_'.$original_id.'_'.$openid;
            $redis = new Redis();
            $redis->set($redis_timu_key,1);
            $redis->set($redis_jf_key,0);

            $this->sendMsg(array(
                'touser'  => $openid,
                'msgtype' => 'text',
                'text' => array(
                    'content' => '快来测试一下你的【面具性格图】吧！请根据第一反应回复答案序号噢~\n\n(1/3)图中的云朵停留在哪个位置，你觉得最好？'
                )
            ), $access_token);

            //图片暂未上传
            $messageimage = array(
                'touser' => $openid,
                'msgtype' => 'image',
                'image' => array('media_id' =>'6XdJ_uYFqb9pUr9cNYFtPXfH9U3nql8QIoeFCdZzqTc')
            );
            $this->sendMsg($messageimage,$access_token);

        }else{
            //修改数据库取消关注状态
        }
    }

    /**
     * 取消关注
     */
    private function unsubscribe_Event($object){
        //获取openid
        $openid = addslashes($object->FromUserName);
        //获取original_id
        $original_id = addslashes($object->ToUserName);
        //实例化token
        $Usermodel = model("UserModel");
        $where['openid'] = $openid;
        $where['originalid'] = $original_id;
        $data['isgz'] = 0;
        $data['qgtime'] = time();
        $data['uptime'] = time();
        $Usermodel = new UserModel();
        $res = $Usermodel->save($data,$where);
        //当前答题编号
        $redis_timu_key = 'timu_'.$original_id.'_'.$openid;
        //当前总积分
        $redis_jf_key = 'jifen_'.$original_id.'_'.$openid;
        $redis = new Redis();
        $redis->rm($redis_timu_key);
        $redis->set($redis_jf_key);
    }

    /**
     * 自定义菜单点击推送关键字事件
     */
    private function click_Event($object){

    }

    /**
     * 接收文本消息
     */
    private function receiveText($object){
        //文本回复
        $keywords = addslashes(trim($object->Content));
        //微信用户openid
        $openid = addslashes($object->FromUserName);
        $original_id = addslashes($object->ToUserName);
        $userinfo=$this->getwuserinfo($openid,$original_id);
        //文本回复
        $redis = new Redis();
        $redis_timu_key = 'timu_'.$original_id.'_'.$openid;
        $redis_jf_key = 'jifen_'.$original_id.'_'.$openid;
        if(!$redis->has($redis_timu_key)){
            $redis->set($redis_timu_key,1);
        }
        $timu = $redis->get($redis_timu_key);
        $access_token = $this->getAccessToken($original_id);
        $ti1 = [1,2,3,4];
        if($timu == 1){
            if(in_array($keywords,$ti1)){
                $this->sendMsg(array(
                    'touser'  => $openid,
                    'msgtype' => 'text',
                    'text' => array(
                        'content' => "(2/3)你觉得下图哪个女生最悲伤？"
                    )
                ), $access_token);
                //图片未做上传
                $messageimage = array(
                    'touser' => $openid,
                    'msgtype' => 'image',
                    'image' => array('media_id' =>'6XdJ_uYFqb9pUr9cNYFtPXfH9U3nql8QIoeFCdZzqTc')
                );
                $this->sendMsg($messageimage,$access_token);
                $redis->set($redis_timu_key,2);
            }else{

                $this->sendMsg(array(
                    'touser'  => $openid,
                    'msgtype' => 'text',
                    'text' => array(
                        'content' => "请输入数字（1、2、3、4）"
                    )
                ), $access_token);
            }
        }else if($timu == 2){
            if(in_array($keywords,$ti1)){
                $this->sendMsg(array(
                    'touser'  => $openid,
                    'msgtype' => 'text',
                    'text' => array(
                        'content' => "(3/3)如果你在森林里迷路，你会选择在哪个房子里过夜？"
                    )
                ), $access_token);
                //图片未做上传
                $messageimage = array(
                    'touser' => $openid,
                    'msgtype' => 'image',
                    'image' => array('media_id' =>'6XdJ_uYFqb9pUr9cNYFtPXfH9U3nql8QIoeFCdZzqTc')
                );
                $this->sendMsg($messageimage,$access_token);
                $redis->set($redis_timu_key,3);
            }else{

                $this->sendMsg(array(
                    'touser'  => $openid,
                    'msgtype' => 'text',
                    'text' => array(
                        'content' => "请输入数字（1、2、3、4）"
                    )
                ), $access_token);
            }
        }else if($timu == 3){
            //结果
            if(in_array($keywords,$ti1)){
                $fen = $redis->get($redis_jf_key);
                $redis->set($redis_jf_key,0);
                $redis->set($redis_timu_key,1);

                $this->sendMsg(array(
                    'touser'  => $openid,
                    'msgtype' => 'text',
                    'text' => array(
                        'content' => $userinfo['nickname']."，这是你的测试结果~长按3秒即可保存！\n赶快分享到朋友圈看看你的人生状态检测报告准不准~！😏"
                    )
                ), $access_token);
                $headfile = 'static/haibao/tmp/rsjcbg/'.time().mt_rand(10000, 99999).'.jpg';//定义图片路径
                $this->save_to_local($userinfo['headimgurl'],$headfile);//下载头像
                // 制作海报过程
                $haibaofile = $this->makeImg($headfile, $userinfo['nickname'], $original_id);
                // 上传图片到临时库
                $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image';
                //图片存到微信服务器
                $info_ = $this->curl_post_file($haibaofile, $url);

                //返回结果字符串转数组
                $arr = json_decode($info_, true);
                //定义（取）media_id
                $media_id = $arr['media_id'];
                $messageimage = array(
                    'touser' => $openid,
                    'msgtype' => 'image',
                    'image' => array('media_id' =>$media_id)
                );
                $this->sendMsg($messageimage,$access_token);
                //删除本地海报
                unlink($haibaofile);
                //删除本地头像
                unlink($headfile);
            }else{
                $this->sendMsg(array(
                    'touser'  => $openid,
                    'msgtype' => 'text',
                    'text' => array(
                        'content' => "请输入数字（1、2、3、4）"
                    )
                ), $access_token);
            }
        }
    }

    /**
     * 接收图片消息
     */
    private function receiveImage($object)
    {
        //$content = array("MediaId"=>$object->MediaId);
        //$result = $this->transmitImage($object, $content);
        //return $result;
    }

    /**
     * 接收位置消息
     */
    private function receiveLocation($object)
    {
        //$content = "".$object->Location_X."".$object->Location_Y."".$object->Scale."".$object->Label;
        //$result = $this->transmitText($object, $content);
        //return $result;
    }

    /**
     * 接收语音消息
     */
    private function receiveVoice($object)
    {
        /* if (isset($object->Recognition) && !empty($object->Recognition)){
             $content = "".$object->Recognition;
             $result = $this->transmitText($object, $content);
         }else{
             $content = array("MediaId"=>$object->MediaId);
             $result = $this->transmitVoice($object, $content);
         }

         return $result;*/
    }

    /**
     * 接收视频消息
     */
    private function receiveVideo($object)
    {
        /* $content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
         $result = $this->transmitVideo($object, $content);
         return $result;*/
    }

    /**
     * 接收链接消息
     */
    private function receiveLink($object)
    {
        //$content = "".$object->Title."".$object->Description."".$object->Url;
        //$result = $this->transmitText($object, $content);
        //return $result;
    }

    /**
     * 回复文本消息
     */
    private function transmitText($object, $content)
    {
        $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[%s]]></Content>
        </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    /**
     * 回复图文消息
     */
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return;
        }
        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
        </item>";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }

        $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <ArticleCount>%s</ArticleCount>
        <Articles>
        $item_str</Articles>
        </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    /**
     * 回复图片消息
     */
    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
        <MediaId><![CDATA[%s]]></MediaId>
        </Image>";

        $item_str = sprintf($itemTpl, $imageArray['MediaId']);

        $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[image]]></MsgType>
        $item_str
        </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    /**
     * 回复语音消息
     */
    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
        <MediaId><![CDATA[%s]]></MediaId>
        </Voice>";

        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);

        $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[voice]]></MsgType>
        $item_str
        </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    /**
     * 回复视频消息
     */
    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
        <MediaId><![CDATA[%s]]></MediaId>
        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        </Video>";

        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

        $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[video]]></MsgType>
        $item_str
        </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    /**
     * 回复音乐消息
     */
    private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
        </Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[music]]></MsgType>
        $item_str
        </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    /**
     * 回复多客服消息
     */
    private function transmitService($object)
    {
        $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[transfer_customer_service]]></MsgType>
        </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    /**
     * 获取用户信息
     */
    public function getwuserinfo($openid, $originalid) {
        $access_token =$this->getAccessToken($originalid);
        // Log::error('$access_token----------------------'.$access_token);
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $wuser = $this-> https_request($url);
        // Log::error('$wuser----------------------'.$wuser);

        $wuser = json_decode($wuser, true);
        return $wuser;
    }

    /**
     * 获取access_token
     */
    public function getAccessToken($original_id) {
        $token_redis_key = "WX_CONFIG:OriginalId:".$original_id;
        $redis = new Redis();
        $wx_config = $redis->get($token_redis_key);
        return $wx_config['access_token'];
    }

    /**
     * 发送http请求
     */
    public function https_request($url, $data = null) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    function callWebApi($url, $data='', $method='GET'){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if($method=='POST'){
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            if ($data != ''){
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
            }
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        curl_close($curl); // 关闭CURL会话
        return json_decode($tmpInfo, true);
    }

    /**
     * 上传图片素材
     */
    public function curl_post_file($file, $url)
    {
        if (class_exists('\CURLFile')) {
            $data = array('media' => new \CURLFile(realpath($file)));
        }else {
            $data = array('media' => '@' . realpath($file));
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if (class_exists('\CURLFile')) {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
        }else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        @curl_setopt($ch, CURLOPT_INFILESIZE,filesize($file));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    function sendMsg($data, $access_token) {
        return $this->callWebApi('https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token, $this->toJson($data),'POST');
    }

    /**
     * 保存网络链接图片到本地
     * $url       网络图片的链接
     * $filename  保存后的本地图片资源路径
     */
    private function save_to_local($url,$filename) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $imageData = curl_exec($curl);
        curl_close($curl);
        $tp = @fopen($filename, 'a');
        fwrite($tp, $imageData);
        return fclose($tp);
    }

    /**
     * 对数据进行转码，避免中文转json时乱码
     * @param array & string $data
     */
    public function toJson($data) {
        $data = json_encode($this->urlencodeAry($data));
        return urldecode($data);
    }

    /**
     * 将数据进行urlencode
     * @param array & string $data
     */
    public function urlencodeAry($data) {
        if(is_array($data)) {
            foreach($data as $key=>$val) {
                $data[$key] = $this->urlencodeAry($val);
            }
            return $data;
        } else {
            return urlencode($data);
        }
    }

    public function makeImg($head,$uname,$original_id) {
        $returnArr['code'] = 1;
        $len = mt_rand(1,12);
        $bg = 'static/haibao/tmp/rsjcbg/bg/'.$len.'.jpg';
        if (is_file($bg)) {
            //定义文件路径
            $uploads_dir = 'static/haibao/tmp/rsjcbg';

            //定义二维码
            // $ewm_rand = mt_rand(1,3);
            $ewm_rand = "gh_f1692fd27f96"; //穿出女神范
            $_qrcode = 'static/haibao/tmp/rsjcbg/ewm/'.$ewm_rand.'.jpg';
            $ewm = \think\Image::open($_qrcode);
            $ewm->thumb(135,135)->save($_qrcode);
            $ewm_locate = array(46,1040);

            $headfile = 'static/haibao/tmp/rsjcbg/hd'.time().'.png';
            //头像
            $headlocate = array(40,135);
            $head = \think\Image::open($head);
            $head->thumb(130,130,\think\Image::THUMB_FIXED)->radius(65)->save($headfile,'png');

            $image = \think\Image::open($bg);
            //定义海报名称
            $imgname = time().mt_rand(0,99999).'.jpg';
            $sum = bcadd(1,2);
            $imagefile = $uploads_dir.'/'.time().$imgname;
            $font = 'static/haibao/fonts/simhei.ttf';
            $font_size = 34;
            // $zw = (strlen($uname) - mb_strlen($uname,'utf8'))/2;//名字中文个数
            // $qt = mb_strlen($uname,'utf8') - $zw;
            // $posx = 375 - $qt*9 - $zw*21;
            $locate1 = array(285,160);
            $res = $image
                ->water($headfile,$headlocate)//头像
                ->text($uname,$font,$font_size,"#1c3c91",$locate1,0,0)
                ->water($_qrcode,$ewm_locate)//二维码
                ->save($imagefile);
            unlink($headfile);
            if($res) {
                return $imagefile;
            }
        }else{
            Log::error($bg);
            Log::error('没有背景图片');
        }
    }
}